import 'dart:io';

import 'package:amap_flutter_location/amap_flutter_location.dart';
import 'package:cave_flutter/common/common_action.dart';
import 'package:cave_flutter/db_manager/bean/whl_product_bean.dart';
import 'package:cave_flutter/model/base_source_model.dart';
import 'package:cave_flutter/model/dynamic_draft_model.dart';
import 'package:cave_flutter/model/dynamic_model.dart';
import 'package:cave_flutter/model/image_model.dart';
import 'package:cave_flutter/model/topic_model.dart';
import 'package:cave_flutter/network/whl_api.dart';
import 'package:cave_flutter/pages/whl_chat/whl_chat_room/record_sheet_view/whl_record_sheet_view.dart';
import 'package:cave_flutter/pages/whl_home/whl_publish/select_visit_widget.dart';
import 'package:cave_flutter/pages/whl_home/whl_publish/sure_exit_publish/sure_exit_publish_view.dart';
import 'package:cave_flutter/utils/imageUtils.dart';
import 'package:cave_flutter/utils/task_utils.dart';
import 'package:cave_flutter/utils/whl_db_utils.dart';

import 'package:cave_flutter/utils/whl_permission_util.dart';
import 'package:cave_flutter/utils/whl_picker_util.dart';
import 'package:cave_flutter/utils/whl_record_voice_utils.dart';
import 'package:cave_flutter/utils/whl_toast_utils.dart';
import 'package:cave_flutter/utils/whl_user_utils.dart';
import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:path_provider/path_provider.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
import 'package:wechat_camera_picker/wechat_camera_picker.dart';

import '../../../routes/whl_app_pages.dart';

class PostsModel {
  String? title;
  String? subTitle;
  String? icon;
  Function? onTap;

  PostsModel({this.title, this.icon, this.onTap, this.subTitle});
}

class AddCavePostLogic extends GetxController {
  List<String> typeList = ['Short', 'Hilarious', 'Funny'];
  int selectedIndex = 0;
  TextEditingController titleController = TextEditingController();

  // TextEditingController describeController = TextEditingController();
  String? imagePath;
  bool isBtnEnable = false;
  RecordVoiceModel? recordVoiceModel;
  DynamicModel? dynamicModel;
  bool isForward = false;

  // bool canPop = false;
  List highListData = [];

  List<TopicModel> selectTopicList = [];
  BaseItemModel? selectVisitModel;
  ImageModel? imageModel;
  Map<String, dynamic> highSetterData = {
    'watermark': 1,
  };
  //  定时发送的时间，send开启后使用
  DateTime? sendTime;

  late AMapFlutterLocation flutterLocation;

  String latitude = "";
  String longitude = "";
  String address = "";
  String province = "";
  String city = "";
  String district = "";
  String adCode = "";
  String cityCode = "";

  int caveId = 0;

  @override
  void onInit() {
    // TODO: implement onInit
    super.onInit();
    var a = Get.arguments;
    if (a != null) {
      dynamicModel = a["model"];
      isForward = a["isForward"] ?? false;
      caveId = a['caveId'];

      if (!isForward) {
        initWithOldModel();
      }
    } else {
      initWithDraft();
    }

    flutterLocation = AMapFlutterLocation();
    // flutterLocation.setLocationOption(AMapLocationOption(
    //     onceLocation: true,
    //     geoLanguage: GeoLanguage.ZH,
    //     locationMode: AMapLocationMode.Hight_Accuracy,
    //     locationInterval:2000,
    //     pausesLocationUpdatesAutomatically:false,
    //     desiredAccuracy:DesiredAccuracy.Best
    // ));
    WhlPermissionUtil.reqLocationWhenInUsePermission(onSuccessAction: () {
      flutterLocation.startLocation();
    });
    flutterLocation.onLocationChanged().listen((event) {
      print("定位结果1");
      print(event);
      latitude = event["latitude"].toString();
      longitude = event["longitude"].toString();
      address = event["address"].toString();
      province = event["province"].toString();
      city = event["city"].toString();
      district = event["district"].toString();
      adCode = event["adCode"].toString();
      cityCode = event["cityCode"].toString();
      if (cityCode != '') {
        flutterLocation.stopLocation();
      }
      update();
    });
    flutterLocation.startLocation();

    update();
  }

  @override
  onReady() {
    super.onReady();
  }

  @override
  onClose() {
    super.onClose();
    flutterLocation.stopLocation();
    flutterLocation.destroy();
  }

  // loadHighSetterData(){
  //   WhlApi.getHighSetList.get({}).then((value) {
  //     if (value.isSuccess()) {
  //       highListData = value.data.map((e) => BaseItemModel.fromJson(e)).toList();
  //       update();
  //     }
  //   });
  // }

  sendDynamicRequest(context) {
    if (titleController.text.isEmpty) {
      MyToast.show('请输入动态内容');
      return;
    }
    if (imageModel != null && imageModel!.imageStatus != 1) {
      MyToast.show('图片上传中，请稍后再试！');
      return;
    }

    if (selectVisitModel?.value == null) {
      MyToast.show('请选择可见范围');
      return;
    }
    if (highSetterData['send'] == 1 && sendTime == null) {
      //  弹出时间
      WhlPickerUtil.showPickerDateTime(context, 4, (picker, selected) {
        sendTime = DateTime.parse(picker.adapter.text);
        sendDynamicRequest(context);
      }, title: '设置定时发布时间');
      return;
    }

    List topics = [];
    for (var value in selectTopicList) {
      Map<String, dynamic> map = {
        "talkId": value.id,
        "talkName": value.talkName
      };
      topics.add(map);
    }
    // Map<String, dynamic> setParam = {
    //   "recommend":0,
    //   "send":0,
    //   "notAnonymousComment":0,
    //   "hideComment":0,
    //   "notComment":0,
    //   "notDownload":0,
    //   "notForward":0,
    //   "watermark":0,
    // };
    Map<String, dynamic> param = {
      "content": titleController.text,
      "audioUrl": recordVoiceModel?.url,
      "audioTime": recordVoiceModel?.time,
      "urls": [
        {"imageUrl": imageModel?.imageUrl}
      ],
      "talks": topics,
      "browsePer": {
        "perId": selectVisitModel?.value,
        "userIds": selectVisitModel?.datas?.join(",")
      },
      "setting": highSetterData,
      "top": highSetterData['pushTop'] == 1 ? {"num": 1} : null,
      "time": sendTime != null
          ? {
              'year': sendTime!.year,
              'month': sendTime!.month,
              'day': sendTime!.day,
              'hour': sendTime!.hour,
              'min': sendTime!.minute,
            }
          : null,
      "latitude": latitude,
      "longitude": longitude,
      "address": address,
      "province": province,
      "city": city,
      "district": district,
      "adCode": adCode,
      "cityCode": cityCode,
      "caveId": caveId
    };
    if (dynamicModel != null && !isForward) {
      param["id"] = dynamicModel!.id;
    }
    WhlApi.addCavePost.post(param).then((value) {
      if (value.isSuccess()) {
        TaskUtils.complateTask(22, type: 3);
        if (dynamicModel != null && !isForward) {
          MyToast.show('编辑成功');
        } else {
          MyToast.show('发布成功');
        }
        WhlUserUtils.removeDynamicDraftModel();
        Get.back(result: true);
      } else {
        MyToast.show('发布失败');
      }
    });
  }

  saveDraft() {
    DynamicDraftModel draftModel = DynamicDraftModel(
      selectTopicList: selectTopicList,
      content: titleController.text,
      audioUrl: recordVoiceModel?.url,
      audioPath: recordVoiceModel?.path,
      imagePath: imagePath,
      url: imageModel?.imageUrl,
      perId: selectVisitModel?.value,
      perName: selectVisitModel?.title,
      userIds: selectVisitModel?.datas?.join(","),
      setting: highSetterData,
    );
    WhlUserUtils.saveDynamicDraftModel(draftModel);
  }

  initWithOldModel() {
    if (dynamicModel != null) {
      selectTopicList = dynamicModel!.talks ?? <TopicModel>[];
      titleController.text = dynamicModel!.content ?? "";
      if ((dynamicModel!.audioUrl ?? "").isNotEmpty) {
        recordVoiceModel = RecordVoiceModel("", 1);
        recordVoiceModel?.url = dynamicModel!.audioUrl ?? "";
      }
      if ((dynamicModel!.urls ?? []).isNotEmpty) {
        if ((dynamicModel!.urls!.first.imageUrl ?? "").isNotEmpty) {
          imageModel = dynamicModel!.urls!.first;
          imageModel!.imageStatus = 1;
        }
      }
      // selectVisitModel = BaseItemModel(title: dynamicModel.perName,value: draftModel.perId,datas: draftModel.userIds?.split(","));
      highSetterData = dynamicModel!.setting?.toJson() ?? {};
      onCheckPostBtnEnable();
      update();
    }
  }

  initWithDraft() {
    DynamicDraftModel? draftModel = WhlUserUtils.getDynamicDraftModel();
    if (draftModel != null) {
      selectTopicList = draftModel.selectTopicList ?? <TopicModel>[];
      titleController.text = draftModel.content ?? "";
      if ((draftModel.audioPath ?? "").isNotEmpty) {
        recordVoiceModel = RecordVoiceModel(draftModel.audioPath ?? "", 0);
        recordVoiceModel?.url = draftModel.audioUrl ?? "";
      }
      if ((draftModel.imagePath ?? "").isNotEmpty) {
        imagePath = draftModel.imagePath ?? "";
        imageModel = ImageModel(
            imageUrl: draftModel.url, imageStatus: 1, imagePath: imagePath);
        if ((draftModel.url ?? "").isEmpty) {
          uploadImageRequest(imageModel!);
        }
      }
      selectVisitModel = BaseItemModel(
          title: draftModel.perName,
          value: draftModel.perId,
          datas: draftModel.userIds?.split(","));
      highSetterData = draftModel.setting ?? {};
      onCheckPostBtnEnable();
      update();
    }
  }

  onCheckPostBtnEnable() {
    if (titleController.text.isNotEmpty) {
      isBtnEnable = true;
    } else {
      isBtnEnable = false;
    }
    update();
  }

  doClickImageAsset() async {
    // WhlBottomActionSheet.show(['拍照', '相册选择'], callBack: (index) {
    //   if (index == 1) {
    selectPhoto();
    //   } else {
    //     takePhoto();
    //   }
    // });
  }

  selectPhoto() {
    WhlPermissionUtil.reqStoragePermission(onSuccessAction: () async {
      List<AssetEntity>? resultList = await AssetPicker.pickAssets(Get.context!,
          pickerConfig: const AssetPickerConfig(
            requestType: RequestType.image,
            maxAssets: 1,
          ));
      if (resultList != null && resultList.isNotEmpty) {
        AssetEntity assetEntity = resultList.first;
        imagePath = (await assetEntity.file)?.path;
        update();
        onCheckPostBtnEnable();

        uploadImage(assetEntity);
      }
    });
  }

  takePhoto() {
    WhlPermissionUtil.reqCameraPermission(onSuccessAction: () async {
      AssetEntity? assetEntity =
          await CameraPicker.pickFromCamera(Get.context!);
      if (assetEntity != null) {
        imagePath = (await assetEntity.file)?.path;
        update();
        onCheckPostBtnEnable();

        uploadImage(assetEntity);
      }
    });
  }

  uploadImage(AssetEntity? assetEntity) async {
    imageModel = ImageModel(
      assetEntity: assetEntity,
      name: assetEntity?.title,
    );
    if (assetEntity != null) {
      String str =
          '【Cave】${WhlUserUtils.getNickName()} ${WhlUserUtils.accountId()}';
      File? waterMarkFile =
          await imageAddWaterMark(assetEntity: assetEntity, text: str);
      if (waterMarkFile != null) {
        imageModel!.assetEntity = null;
        imageModel!.imagePath = waterMarkFile.path;
        imagePath = waterMarkFile.path;
      }
    }
    uploadImageRequest(imageModel!, callBack: (model, isSuccess) {
      if (isSuccess) {
        update();
      } else {
        imageModel = null;
        imagePath = null;
        MyToast.show('上传失败');
      }
    });
  }

  uploadVoice() {
    uploadVoiceRequest(recordVoiceModel!, callBack: (model, isSuccess) {
      if (isSuccess) {
        update();
      } else {
        recordVoiceModel = null;
        MyToast.show('上传失败');
      }
    });
  }

  doClickPost() async {
    Directory? directory = await getApplicationDocumentsDirectory();
    String path = directory!.path;
    String filePath = '$path/${DateTime.now().millisecondsSinceEpoch}.png';
    File logicFile = File(imagePath!);
    if (logicFile.existsSync()) {
      await logicFile.copy(filePath);
    }
    WhlDBUtils.instance.productDao.insertProduct(WhlProductBean(
      title: titleController.text,
      // describe: describeController.text,
      cover: filePath,
      nickname: WhlUserUtils.getNickName(),
      avatar: WhlUserUtils.getAvatar(),
      userId: WhlUserUtils.getId(),
      type: typeList[selectedIndex],
      isFollowed: false,
      isLike: false,
      isFriend: false,
      isMultiple: false,
      likeNum: 0,
      followNum: 0,
    ));
    Future.delayed(Duration(milliseconds: 500)).then((value) {
      MyToast.show('Post Success');
      Get.back();
    });
  }

  doClickVoiceRecord() {
    WhlPermissionUtil.reqMicrophonePermission(onSuccessAction: () {
      Get.bottomSheet(WhlRecordSheetPage(), isScrollControlled: false)
          .then((value) {
        if (value != null) {
          RecordVoiceModel model = value as RecordVoiceModel;
          print('音频设置');
          print(model.path);
          recordVoiceModel = model;
          update();
          uploadVoice();
        }
      });
    });
  }

  showSelectVisitView() async {
    var result = await Get.bottomSheet(SelectVisitWidget(
      oldSelectModel: selectVisitModel,
    ));
    if (result != null) {
      selectVisitModel = result;
      update();
    }
  }

  Future<void> toTopicPage() async {
    var result = await Get.toNamed(Routes.topicList);
    if (result != null) {
      for (var value in selectTopicList) {
        if (value.id == result.id) {
          return;
        }
      }
      selectTopicList.add(result);
      update();
    }
  }

  void deleteImage() {
    imagePath = null;
    imageModel = null;
    update();
  }

  Future<void> backAction() async {
    if (titleController.text.isNotEmpty || (imagePath ?? "").isNotEmpty) {
      var result = await Get.bottomSheet(SureExitPublishSheet());
      if (result != null) {
        if (result == true) {
          saveDraft();
        }
        // WhlUserUtils.removeDynamicDraftModel();
        Get.back();
      }
    } else {
      Get.back();
    }
  }
}
